function showInfoWindow(position, queryResult) {
    var features = queryResult.features;
    if (features.length == 0) {
        removeAllEntities();
        $("#queryResult").hide();
        showMsgLayer("查询结果为空！");
    } else {
        var rows = [];
        var fields = [];
        var allFeatures = features;
        var firstFeatureProp = features[0].properties;
        for (var key in firstFeatureProp) {
            fields.push(key);
        }
        var content = "<table><tbody>";
        for (var k = 0; k < fields.length; k++) {
            var fieldName = fields[k];
            var fieldAlise = fieldName;
            if (fieldName == "OBJECTID") {
                continue;
            }
            if (fieldName == "SHAPE_Area") {
                continue;
            }
            if (fieldName == "SHAPE_Leng") {
                continue;
            }
            content += "<tr><th>";
            if (fields[k] == "MODEL_NAME")
                fieldAlise = "模型名称";
            if (fields[k] == "MinHeight")
                fieldAlise = "最低高度";
            if (fields[k] == "MaxHeight")
                fieldAlise = "最高高度";
            if (fields[k] == "x")
                fieldAlise = "经度";
            if (fields[k] == "y")
                fieldAlise = "纬度";
            if (fields[k] == "Height")
                fieldAlise = "房高";
            content += fieldAlise;
            content += ":</th><td>";
            if (fields[k].indexOf("Height") != -1) {
                content += firstFeatureProp[fields[k]].toFixed(2);
            } else {
                content += firstFeatureProp[fields[k]];
            }
            content += "</td></tr>";
        }
        content += "</tbody></table>";
        var obj = { position: position, content: content };
        infoWindow(obj);
    }
}

function changeFeaturesForMap3DTable(results,isQueryAll) {
    removeAllEntities();
    var queryResult = results[0].data;
    var layerId = results[0].id;
    if (!queryResult || !queryResult.features || queryResult.features.length == 0) {
        removeAllEntities();
        $("#queryResult").hide();
        showMsgLayer("查询结果为空！");
        layui.layer.msg("查询结果为空!",{icon:5});
    } else {
        var features = queryResult.features;
        var rows = [];
        var fields = [];
        var allFeatures = features;
        var firstFeatureProp = features[0].properties;
        var AttributeFilter = getFieldsInfo(layerId);
        var fieldsFromAttributeFilter = true;
        if (AttributeFilter.length == "0") {
            for (var key in firstFeatureProp) {
                fields.push(key);
            }
            fieldsFromAttributeFilter = false;
        } else {
            for (var k in AttributeFilter) {
                if (AttributeFilter[k].isquery == "1") {
                    fields.push({
                        fieldname: AttributeFilter[k].fieldname,
                        fieldalias: AttributeFilter[k].fieldalias
                    });
                }
            }
            fieldsFromAttributeFilter = true;
        }
        features = [];
        for (var i = 0; i < allFeatures.length; i++) {
            features.push(allFeatures[i].properties);
        }

        //将查询结果拼接成json格式数据
        for (var j = 0; j < features.length; j++) {
            var feature = features[j];
            var row = {};
            for (var k = 0; k < fields.length; k++) {
                if (fieldsFromAttributeFilter) {
                    var fieldName = fields[k].fieldname;
                    var fieldalias = fields[k].fieldalias;
                    if (fieldName == "AREA") {
                        row[fieldName] = parseFloat(feature[fields[k].fieldname]).toFixed(2);
                        continue;
                    }
                    if(feature[fieldName] == undefined){
                        row[fieldalias] = feature[fieldalias];
                    }else{
                        row[fieldalias] = feature[fieldName];
                    }
                } else {
                    var fieldName = fields[k];
                    if (fieldName == "AREA") {
                        row[fieldName] = parseFloat(feature[fields[k]]).toFixed(2);
                        continue;
                    }
                    row[fieldName] = feature[fields[k]];
                }
            }
            row["geom"] = JSON.stringify(allFeatures[j].geometry);
            rows.push(row);
        }

        var contentJson = {
            "total": features.length,
            "totalNotFiltered": features.length,
            "rows": rows
        };
        var titles = [];
        for (var i = 0; i < fields.length; i++) {
            var field = null;
            if (fieldsFromAttributeFilter) {
                field = fields[i].fieldalias;
            } else {
                field = fields[i];
            }
            titles.push(field);
        }
        titles.push("geom");
        createTable(titles, contentJson,layerId,isQueryAll);
        if(isQueryAll){
            addQueryFeatures(allFeatures,true);
        }else{
            addQueryFeatures(allFeatures);
        }
        layui.layer.msg("查询成功",{icon:1});
    }
}

function createTable(titles, contentJson,id,isQueryAll) {
    $("#queryTable").html("<div id='queryTable_tab0' lay-filter='queryTable_tab0'></div>");
    $("#queryResult").show();
    var colsArr = [];
    var a = [];
    for (var i = 0; i < titles.length; i++) {
        var obj = {
            field: titles[i],
            title: titles[i],
            width: 100,
            sort: true
        }
        if (titles[i] == "geom") {
            obj.hide = true;
        }
        a.push(obj);
    }
    colsArr.push(a);
    table.render({
        elem: '#queryTable_tab0',
        height: 312,
        toolbar: '#toolbarDemo',
        defaultToolbar: ['filter', 'exports', 'print'],
        data: contentJson.rows,
        page: true, //开启分页
        cols: colsArr,
        text: {
            none: '暂无数据'
        },
        done:function(res, curr, count){
            $(".layui-table-page .layui-laypage button, .layui-table-page .layui-laypage input").css("margin-top", "0px");
        }
    });
    table.on('row(queryTable_tab0)', function (obj) {
        // 地类图斑溯源，只有 地类图斑ChuS 可以显示溯源按钮 
        // 点击表格的每行，，表格头部出现溯源按钮，点击溯源按钮获取，考虑在哪个位置隐藏溯源按钮，
        if(id == "Eb96541E98F542AD9Dc19af2934DeD2B"){
            layui.table.reload('#queryTable_tab0',{
                elem: '#queryTable_tab0',
                toolbar:true,
                toolbar:'#searchDLTBSource',
                done:function(res, curr, count){
                    $(".layui-table-page .layui-laypage button, .layui-table-page .layui-laypage input").css("margin-top", "0px");
                    $('#btn_searchDLTBSource').click(function(evt){
                        layer.closeAll('iframe'); //关闭所有的iframe层
                        var itemId = obj.data["OBJECTID"]
                        var url = '/MapServer/Portal/searchDLTBSource.html?id= ' + itemId + '';
                        layer.open({
                            type: 2,
                            title: "溯源结果展示",
                            content: url,
                            offset: ['80px','60%'],
                            shade: 0,
                            area:["600px","400px"]
                        });
                    })
                }
            })
        }
        if (obj.data.geom) {
            if(isQueryAll){
                addSelectedFeature(JSON.parse(obj.data.geom),true);
            }else{
                addSelectedFeature(JSON.parse(obj.data.geom));
            }
        }
    });
    // $(".layui-laypage select option").css("background", "#213457");
}
//根据guid从后台获取属性字段
function getFieldsInfo(guid) {
    var modelURL = getBaseplatformPort();
    $.ajax({
        type: "post",
        async: false,
        url: modelURL + "resource/getServiceFiled",
        data: {
            layerGuid: guid
        },
        datatype: "json",
        success: function (result) {
            var data = JSON.parse(result);
            thisResult = data.data;
        },
        error: function (err) { }
    });
    return thisResult;
}
function changeFeaturesForTabTable(queryResults, copy) {
    removeAllEntities();
    if (queryResults.length > 0) {
        $("#queryTable").html("");
        $("#queryResult").show();
        var html = '<div class="layui-tab">';
        var tabTitle = '<ul class="layui-tab-title">';
        var tabContent = '<div class="layui-tab-content">';
        for (var i = 0; i < queryResults.length; i++) {
            tabContent += '<div class="layui-tab-item ' + (i == 0 ? "layui-show" : "") + '"><table lay-filter="queryTable_' + queryResults[i].id + '" id="queryTable_' + queryResults[i].id + '"></table></div>';
            tabTitle += '<li ' + (i == 0 ? 'class="layui-this"' : "") + '>' + queryResults[i].name + '</li>';
        }
        tabTitle += '</ul>';
        tabContent += '</div>';
        html += tabTitle + tabContent + '</div>';

        $("#queryTable").html(html);
        for (var y = 0; y < queryResults.length; y++) {
            var queryResult = queryResults[y].data;
            var features = queryResult.features;
            var rows = [];
            var fields = [];
            var allFeatures = features;
            var firstFeatureProp = features[0].properties;
            var AttributeFilter = getFieldsInfo(queryResults[y].id);
            var fieldsFromAttributeFilter = true;
            if (AttributeFilter.length == "0") {
                for (var key in firstFeatureProp) {
                    // if (key && key.toLowerCase().indexOf("shape") == -1 && key.toLowerCase().indexOf("object") == -1) {
                    //     fields.push(key);
                    // }
                    fields.push(key);
                }
                fieldsFromAttributeFilter = false;
            } else {
                for (var k in AttributeFilter) {
                    if (AttributeFilter[k].isquery == "1") {
                        fields.push({
                            fieldname: AttributeFilter[k].fieldname,
                            fieldalias: AttributeFilter[k].fieldalias
                        });
                    }
                }
                fieldsFromAttributeFilter = true;
            }

            //fields
            features = [];
            for (var i = 0; i < allFeatures.length; i++) {
                // 绘制结果 
                // var dataArr = allFeatures[i].geometry.coordinates[0][0];
                // var newdata = ToWGS84(dataArr, true);
                // addClapFeature(newdata);
                features.push(allFeatures[i].properties);
            }

            //将查询结果拼接成json格式数据
            for (var j = 0; j < features.length; j++) {
                var feature = features[j];
                var row = {};
                for (var k = 0; k < fields.length; k++) {
                    if (fieldsFromAttributeFilter) {
                        var fieldName = fields[k].fieldname;
                        var fieldalias = fields[k].fieldalias;
                        if (fieldName == "AREA") {
                            row[fieldName] = parseFloat(feature[fields[k].fieldname]).toFixed(2);
                            continue;
                        }
                        //row[fieldName] = feature[fields[k]];
                        row[fieldalias] = feature[fieldName];
                    } else {
                        var fieldName = fields[k];
                        if (fieldName == "AREA") {
                            row[fieldName] = parseFloat(feature[fields[k]]).toFixed(2);
                            continue;
                        }
                        row[fieldName] = feature[fields[k]];
                    }
                }
                row["geom"] = JSON.stringify(allFeatures[j].geometry);
                row["arcgis"] = JSON.stringify(allFeatures[j].arcgis);
                rows.push(row);
            }

            var contentJson = {
                "total": features.length,
                "totalNotFiltered": features.length,
                "rows": rows
            };
            var titles = [];
            //根据查询结果构建列
            var columns = [];

            for (var i = 0; i < fields.length; i++) {
                var field = null;
                if (fieldsFromAttributeFilter) {
                    field = fields[i].fieldalias;
                    // if (fields[i].fieldname.toLowerCase() == "objectid") {
                    //     continue;
                    // }
                } else {
                    field = fields[i];
                    // if (field.toLowerCase() == "objectid") {
                    //     continue;
                    // }
                }
                titles.push(field);
            }
            titles.push("geom");
            createTabTable(titles, contentJson, queryResults[y].id, copy);
            addQueryFeatures(allFeatures);
        }
    } else {
        removeAllEntities();
        $("#queryResult").hide();
        showMsgLayer("查询结果为空！");
    }
}
function createTabTable(titles, contentJson, id, copy) {
    var colsArr = [];
    var a = [];
    if (id == "edCf7a0D54F74acEa6db5890f4F31A1B") {
        a.push({ field: 'file', title: '附件', width: 65, templet: '#fileTool', unresize: true });
    }
    if (copy) {
        a.push({ field: 'copy', title: '操作', width: 65, templet: '#copyBoxTpl', unresize: true });
    }
    for (var i = 0; i < titles.length; i++) {
        var obj = {
            field: titles[i],
            width: 100,
            sort: true,
            //title: '<span title="' + titles[i] + '">' + titles[i] + '</span>'
            title: titles[i]
        }
        if (titles[i] == "geom") {
            obj.hide = true;
        }
        a.push(obj);
    }
    colsArr.push(a);
    layui.table.render({
        elem: '#queryTable_' + id,
        id:'#queryTable_' + id,
        height: 312,
        toolbar: '#toolbarDemo',
        defaultToolbar: ['filter', 'exports', 'print'],
        data: contentJson.rows,
        page: true, //开启分页
        cols: colsArr,
        size: "sm",
        text: {
            none: '暂无数据'
        },
        done:function(res, curr, count){
            $(".layui-table-page .layui-laypage button, .layui-table-page .layui-laypage input").css("margin-top", "0px");
        }
    });
    layui.table.on('row(queryTable_' + id + ')', function (obj) {
        // 地类图斑溯源，只有 地类图斑ChuS 可以显示溯源按钮 
        // 点击表格的每行，，表格头部出现溯源按钮，点击溯源按钮获取，考虑在哪个位置隐藏溯源按钮，
        if(id == "Eb96541E98F542AD9Dc19af2934DeD2B"){
            layui.table.reload('#queryTable_' + id,{
                elem: '#queryTable_' + id,
                toolbar:true,
                toolbar:'#searchDLTBSource',
                done:function(res, curr, count){
                    $(".layui-table-page .layui-laypage button, .layui-table-page .layui-laypage input").css("margin-top", "0px");
                    $('#btn_searchDLTBSource').click(function(evt){
                        layer.closeAll('iframe'); //关闭所有的iframe层
                        var itemId = obj.data["图斑编号"]
                        var url = '/MapServer/Portal/searchDLTBSource.html?id= ' + itemId + '';
                        layer.open({
                            type: 2,
                            title: "溯源结果展示",
                            content: url,
                            offset: ['80px','60%'],
                            shade: 0,
                            area:["600px","400px"]
                        });
                    })
                }
            })
        }
        if (obj.data.geom) {
            addSelectedFeature(JSON.parse(obj.data.geom));
        }
    });
    layui.$('.copydemo').on('click', function (evt) {
        window.parent.parent.$(".json-textarea").show();
        window.parent.parent.$(".json-textarea").val(evt.target.value);
        evt.stopPropagation();
    });
    layui.$('.filedemo').on('click', function (evt) {
        var ywdcbh = evt.target.value;
        openOtherFileList("ywdc", ywdcbh);
        evt.stopPropagation();
    });
    // $(".layui-laypage select option").css("background", "#213457");
}

//链接附件
var g_swiper;
function openOtherFileList(type, value) {
    $.ajaxSettings.async = false;
    var photoList = [];
    var videoList = [];
    switch (type) {
        case "ywdc":
            var queryUrl = "http://192.168.100.201:6080/arcgis/rest/services/SXCMCXQ/ZPGLTJB/MapServer/0/query?where=ywdcbh='" + value + "'&text=&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=*&returnGeometry=false&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=&having=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&historicMoment=&returnDistinctValues=false&resultOffset=&resultRecordCount=&queryByDistance=&returnExtentOnly=false&datumTransformation=&parameterValues=&rangeValues=&quantizationParameters=&f=json";
            $.get(queryUrl, function (data, status) {
                if (typeof (data) === "string") {
                    data = JSON.parse(data)
                }
                for (var i = 0 ; i < data.features.length ; i++) {
                    var attr = data.features[i].attributes;
                    photoList.push("http://192.168.100.111:8081/WYDC/" + attr.path.replaceAll("\\","/") + "/" + attr.Name);
                }
            });
            queryUrl = "http://192.168.100.201:6080/arcgis/rest/services/SXCMCXQ/MVGLTJB/MapServer/0/query?where=ywdcbh='" + value + "'&text=&objectIds=&time=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&relationParam=&outFields=*&returnGeometry=false&returnTrueCurves=false&maxAllowableOffset=&geometryPrecision=&outSR=&having=&returnIdsOnly=false&returnCountOnly=false&orderByFields=&groupByFieldsForStatistics=&outStatistics=&returnZ=false&returnM=false&gdbVersion=&historicMoment=&returnDistinctValues=false&resultOffset=&resultRecordCount=&queryByDistance=&returnExtentOnly=false&datumTransformation=&parameterValues=&rangeValues=&quantizationParameters=&f=json";
            $.get(queryUrl, function (data, status) {
                if (typeof (data) === "string") {
                    data = JSON.parse(data)
                }
                for (var i = 0 ; i < data.features.length ; i++) {
                    var attr = data.features[i].attributes;
                    videoList.push("http://192.168.100.111:8081/WYDC/" + attr.path.replaceAll("\\", "/") + "/" + attr.Name);
                }
            });
            break;
        default:
            break;
    }

    if (photoList.length || videoList.length ) {
        $("#attachment").show();
        var html = "";
        for (var i = 0 ; i < photoList.length ; i++) {
            html += "<div class='swiper-slide'><img src='" + photoList[i] + "' /></div>";
        }
        for (var i = 0 ; i < videoList.length ; i++) {
            html += "<div class='swiper-slide'><video src='" + videoList[i] + "'  controls='controls'></video></div>";
        }
        $(".swiper-wrapper").html(html);
        if (g_swiper) g_swiper.destroy();
        g_swiper = new Swiper('.swiper-container', {
            pagination: {
                el: '.swiper-pagination',
                clickable: true,
                renderBullet: function (index, className) {
                    if (index >= photoList.length) {
                        return '<span class="' + className + '">视频' + (index - photoList.length + 1) + '</span>';
                    }
                    return '<span class="' + className + '">照片' + (index + 1) + '</span>';
                },
            },
        });
    } else {
        showMsgLayer("未检索到附件！");
    }
}

function addSelectedFeature(geom,isAllAttrQuery) {
    viewer.entities.removeById("selected_entity");
    var geomtype = geom.type.toLowerCase();
    var entity = null;
    var destination;
    if (geomtype.indexOf("polygon") > -1) {
        var points = [];
        for (var i = 0; i < geom.coordinates[0][0].length; i++) {
            if(isAllAttrQuery){
                var lon = geom.coordinates[0][0][i][0];
                var lat = geom.coordinates[0][0][i][1];
                var zuobiao = degreesFromWebMercatorProjection([lon, lat])
                points.push(zuobiao.longitude);
                points.push(zuobiao.latitude);
            }else{
                points.push(geom.coordinates[0][0][i][0]);
                points.push(geom.coordinates[0][0][i][1]);
            }
        }
        destination = Cesium.Cartesian3.fromDegreesArray(points);
        entity = viewer.entities.add({
            id: 'selected_entity',
            name: 'selected_entity',
            polygon: {
                hierarchy: destination,
                material: Cesium.Color.GREEN.withAlpha(0.7)
            }
        });
    } else if (geomtype.indexOf("polyline") > -1) {
        entity = viewer.entities.add({
            id: 'selected_entity',
            name: 'selected_entity',
            polyline: {
                positions: destination,
                material: Cesium.Color.GREEN.withAlpha(0.7)
            }
        });
    } else if (geomtype.indexOf("point") > -1) {
        destination = Cesium.Cartesian3.fromDegrees(geom.coordinates[0], geom.coordinates[1]);
        entity = viewer.entities.add({
            id: 'selected_entity',
            name: 'selected_entity',
            position: destination,
            point: {
                color: Cesium.Color.GREEN.withAlpha(0.7),
                pixelSize: 10,
                heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                outlineColor: Cesium.Color.YELLOW,
                outlineWidth: 2,
            }
        });
    }
    if (entity) {
        viewer.flyTo(entity, {
            offset: {
                heading: Cesium.Math.toRadians(0.0),
                pitch: Cesium.Math.toRadians(-90),
                range: 0
            }
        });
    }
}

function addQueryFeatures(features,isProjectionCoordinate) {
    for (var m = 0; m < features.length; m++) {
        var geom = features[m].geometry;
        var geomtype = geom.type.toLowerCase();
        if (geomtype.indexOf("polygon") > -1) {
            var points = [];
            for (var i = 0; i < geom.coordinates[0][0].length; i++) {
                if(isProjectionCoordinate){
                    var lon = geom.coordinates[0][0][i][0];
                    var lat = geom.coordinates[0][0][i][1];
                    var zuobiao = degreesFromWebMercatorProjection([lon, lat])
                    points.push(zuobiao.longitude);
                    points.push(zuobiao.latitude);
                }else{
                    points.push(geom.coordinates[0][0][i][0]);
                    points.push(geom.coordinates[0][0][i][1]); 
                }
            }
            viewer.entities.add({
                polygon: {
                    hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
                    material: Cesium.Color.RED.withAlpha(0.5)
                }
            });
        } else if (geomtype.indexOf("polyline") > -1) {

        } else if (geomtype.indexOf("point") > -1) {
            viewer.entities.add({
                position: Cesium.Cartesian3.fromDegrees(geom.coordinates[0], geom.coordinates[1]),
                point: {
                    color: Cesium.Color.RED.withAlpha(0.5),
                    pixelSize: 10,
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                    outlineColor: Cesium.Color.YELLOW,
                    outlineWidth: 2,
                }
            });
        }
    }
}

function closeQueryToolbar() {
    removeAllEntities();
    pointHandler && pointHandler.clear();
    polylineHandler && polylineHandler.clear();
    polygonHandler && polygonHandler.clear();
};
function degreesFromWebMercatorProjection(cartesian) {
    var webMercatorProjection = new Cesium.WebMercatorProjection();
    var cartographic = new Cesium.Cartographic();
    var param = new Cesium.Cartesian3(cartesian[0], cartesian[1])
    cartographic = webMercatorProjection.unproject(param)
    cartographic.longitude = Cesium.Math.toDegrees(cartographic.longitude);
    cartographic.latitude = Cesium.Math.toDegrees(cartographic.latitude);
    return cartographic;
}